import pymssql

def connn():
    connect = pymssql.connect(
        host='127.0.0.1',  # 本地的
        port='1433',  # 本地的
        user='sa',
        password='123456',  # 本地的
        database='plane',
        charset = 'GBK'
                  # 本地的
    )  # 服务器名,账户,密码,数据库名
    if connect:
        print("lianjie")
    return connect

def write_score(T_username,T_score):
    conn = connn()
    cur = conn.cursor()

    cursor = conn.cursor(as_dict=True)

    i = 0
    T_flag = 0
    cursor.execute('SELECT * FROM P_score ')
    for row in cursor:
        if row['username'] == T_username:
            print("hihi"+T_username+row['username'])
            T_flag = 1
            if row['score'] < T_score:
                sql = 'update p_score set score = ' + str(T_score) + ' where username=\'' + T_username + '\';COMMIT'
                cur.execute(sql)
                break
    print(str(T_flag))
    cursor.execute('SELECT * FROM users ')
    for row in cursor:
        if row['username'] == T_username and T_flag == 0:
            sql = 'insert into p_score values (\''+T_username+'\','+str(T_score)+');COMMIT'
            print("insert " + T_username + str(T_score))
            cur.execute(sql)
            break
    T_flag = 0
    cur.close()
    conn.close()


